#include "MapperNROM.h"
#include "Log.h"

PNE_NAMESPACE_BEGIN

MapperNROM::MapperNROM(Cartridge &cart)
    : Mapper(cart, Mapper::Type::NROM)
{
    if (cart.GetROM().size() == 0x4000) // 1 bank
    {
        m_oneBank = true;
    }
    else // 2 ban
    {
        m_oneBank = false;
    }

    if (cart.GetVROM().size() == 0)
    {
        m_usesCharacterRAM = true;
        m_characterRAM.resize(0x2000);
        LOG(Level::Info) << "Uses character RAM" << std::endl;
    }
    else
        m_usesCharacterRAM = false;
}

Byte MapperNROM::ReadPRG(Address addr)
{
    if (!m_oneBank)
        return m_cartridge.GetROM()[addr - 0x8000];
    else // mirrored
        return m_cartridge.GetROM()[(addr - 0x8000) & 0x3fff];
}

void MapperNROM::WritePRG(Address addr, Byte value)
{
    LOG(Level::InfoVerbose) << "ROM memory write attempt at " << +addr << " to set " << +value << std::endl;
}

Byte MapperNROM::ReadCHR(Address addr)
{
    if (m_usesCharacterRAM)
        return m_characterRAM[addr];
    else
        return m_cartridge.GetVROM()[addr];
}

void MapperNROM::WriteCHR(Address addr, Byte value)
{
    if (m_usesCharacterRAM)
        m_characterRAM[addr] = value;
    else
        LOG(Level::Info) << "Read-only CHR memory write attempt at " << std::hex
                         << addr << std::endl;
}

PNE_NAMESPACE_END
// DONE